extends Node2D

var spawners
var total_score = 0
var collected_counter = 0
var collected_in_row_counter = 0
var not_collected_in_row_counter = 0
var score_ui

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	GameManager.last_level_score = 0
	spawners = get_children()
	assert(spawners != null)
	assert(spawners.size() != 0)
	await get_tree().create_timer(0.1).timeout
	add_to_group("spawn_manager")
	
	spawn_random()
	score_ui  = get_tree().get_first_node_in_group("score_ui")
	



# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass

func pick_random_spawner():
	var r = randi_range(0, spawners.size() - 1)
	return spawners[r]

func pick_random_spawner_valid():
	var _spawner = null
	_spawner = pick_random_spawner()
	if _spawner.has_method("is_player_inside"):
		if _spawner.is_player_inside() or _spawner.spawner_enabled == false:
			_spawner = pick_random_spawner_valid()
		else:
			return _spawner

	return _spawner

func spawn_random():
	var spawner = pick_random_spawner_valid()
	spawner.spawn_item()
	
func add_to_score(amount):
	var add_to = 0
	if amount > 0:
		collected_counter +=1
		collected_in_row_counter +=1
		not_collected_in_row_counter = 0
		add_to = floori(amount) * collected_in_row_counter
	elif amount < 0:
		collected_in_row_counter = 0
		not_collected_in_row_counter +=1
		add_to = floori(amount) * not_collected_in_row_counter
	
	
	total_score += add_to
	if score_ui != null and score_ui.has_method("score_changed"):
		score_ui.score_changed(total_score)
	GameManager.last_level_score = total_score
	print (total_score)
	if total_score <= -50:
		print ("game over - score is below -50")
	else:
		spawn_random()
		
